<template>
  <Dialog
    v-model="dialogVisible"
    :scroll="true"
    :title="dialogTitle"
  >
    <Form ref="formRef" v-loading="formLoading" :rules="formRules" :schema="allSchemas.formSchema" />
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import * as WalletApi from '@/api/pay/wallet/balance'
import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('人工充值') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const userId = ref('')
const open = async (id?: number) => {
  dialogVisible.value = true
  // 修改时，设置数据
  if (id) {
    userId.value = id
    formLoading.value = true
    try {
      // const data = await MailTemplateApi.getMailTemplate(id)
      // formRef.value.setValues(data)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const formRules = reactive({
  price: [required],
})

const crudSchemas = reactive<CrudSchema[]>([
  { label: '金额', field: 'price' },
])
const { allSchemas } = useCrudSchemas(crudSchemas)

const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.getElFormRef().validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formRef.value.formModel
    await WalletApi.walletRechargeCreate({
      userId: unref(userId),
      ...data
    })
    // message.success(t('common.updateSuccess'))
    ElMessage.success('操作成功')
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped lang="scss"></style>
